//
//  CategoryInfoDao.m
//  JiaoX
//
//  Created by yinqy on 15/2/2.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "CategoryInfoDao.h"
#import "FMDatabase.h"


#define CATEGORY_INFO @"category_info"
#define TABLENAME @"TB_CATEGORY_INFO"

@interface CategoryInfoDao()
{
    FMDatabase *db;
    NSString *database_path;
}
@end
@implementation CategoryInfoDao
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documents = [paths objectAtIndex:0];
        database_path = [documents stringByAppendingPathComponent:DB_NAME];
        db = [FMDatabase databaseWithPath:database_path];
        
        [self createTable];
    }
    return self;
}

/**
 *  创建表
 */
- (void)createTable{
    //sql 语句
    if ([db open]) {
        NSString *sql =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (_id integer primary key autoincrement,'%@' blob,key1 varchar(100),key2 varchar(100),key3 varchar(100),key4 varchar(100),key5 varchar(100))",TABLENAME,CATEGORY_INFO];
        BOOL res = [db executeUpdate:sql];
        if (!res) {
            JXLog(@"error when creating home db table");
        } else {
            JXLog(@"success to creating home db table");
        }
        [db close];
    }
}


-(CategoryInfo *)getCategoryInfo;{
    if ([db open]) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",TABLENAME];
        FMResultSet * rs = [db executeQuery:sql];
        if ([rs next]) {
            NSData *homeInfoData = [rs objectForColumnName:CATEGORY_INFO];
            NSDictionary *homeInfoDic = [NSKeyedUnarchiver unarchiveObjectWithData:homeInfoData];
            CategoryInfo *page = [CategoryInfo objectWithKeyValues:homeInfoDic];
            return page;
        }
    }
    return nil;
}

-(BOOL)saveCategoryInfo:(CategoryInfo *)info{
    NSDictionary *dic = [info keyValues];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    if ([db open]) {
        //先清空表里面的内容
        [db executeUpdate:[NSString stringWithFormat:
                           @"DELETE FROM '%@'",
                           TABLENAME]];
        //再添加新数据
        BOOL res = [db executeUpdate:@"INSERT INTO TB_CATEGORY_INFO (category_info) VALUES (?);",data];
        if (!res) {
            JXLog(@"error when insert db table");
        } else {
            JXLog(@"success to insert db table");
        }
        [db close];
        return res;
    }
    return NO;
}
@end
